<template>
  <div>
    <!--我的地址表格-->
    <el-card>
      <el-row :gutter="24">
        <el-col style="text-align: right">
          <el-button type="primary" size="mini" @click="handleAdd">添加地址</el-button>
        </el-col>
      </el-row>

      <el-table stripe border :data="addressData">
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="address" label="地址">
        </el-table-column>
        <el-table-column prop="name" label="名称">
        </el-table-column>
        <el-table-column prop="phone" label="联系电话">
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!--设置默认收货地址的单选按钮-->
            <el-switch
                v-model="scope.row.isDefault"
                @change="setDefault(scope.row)"
                active-color="#13ce66"
                inactive-color="#C0C4CC">
            </el-switch>
          </template>

        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip :enterable="false" effect="dark" content="编辑" placement="top">
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)" size="mini" icon="el-icon-edit">
                编辑
              </el-button>
            </el-tooltip>
            <el-tooltip :enterable="false" effect="dark" content="删除" placement="top">
              <el-button type="danger" @click="handleDelete(scope.$index, scope.row)"
                         size="mini" icon="el-icon-delete">删除
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--新增地址对话框-->
    <div>
      <el-dialog
          title="新增地址"
          :visible.sync="dialogVisible1"
          width="30%"
          :before-close="handleClose">
        <el-form ref="newAddressRef" :rules="rules" label-position="right"
                 label-width="80px" :model="newAddress">
          <el-form-item prop="address" label="地址">
            <el-input v-model="newAddress.address"></el-input>
          </el-form-item>
          <el-form-item prop="name" label="名称">
            <el-input v-model="newAddress.name"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="联系电话">
            <el-input v-model="newAddress.phone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onAdd">添加地址</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <!--修改地址对话框-->
    <div>
      <el-dialog
          title="修改地址"
          :visible.sync="dialogVisible2"
          width="30%"
          :before-close="handleClose">
        <el-form ref="updateAddressRef" :rules="rules" label-position="right" label-width="80px" :model="updateAddress">
          <el-form-item prop="address" label="地址">
            <el-input v-model="updateAddress.address"></el-input>
          </el-form-item>
          <el-form-item prop="name" label="名称">
            <el-input v-model="updateAddress.name"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="联系电话">
            <el-input v-model="updateAddress.phone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="update">修改地址</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyAddress",
  inject: ['reload'],
  data() {
    // 电话号码验证
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100);
    };
    return {
      dialogVisible1: false,  //新增弹出框
      dialogVisible2: false,  //修改弹出框
      addressData: [],    // 获取用户地址记录
      // 新增地址信息
      newAddress: {
        address: '',
        name: '',
        phone: ''
      },
      //修改地址信息
      updateAddress: {
        id: null, //要修改的id
        address: '',
        name: '',
        phone: '',
        isDefault: ''
      },
      rules: {
        address: [
          {required: true, message: '地址不可为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '名称不可为空', trigger: 'blur'}
        ],
        phone: [
          {required: true, trigger: 'blur', validator: checkPhone}
        ]
      },
    }

  },
  // 获取用户地址列表
  created() {
    this.getAddressList();
  },
  methods: {
    getAddressList() {
      this.$axios.get("/user/address", {
        params:
            {id: this.$store.state.user.id}
      }).then(response => {
        if (response.data.success) {
          this.addressData = response.data.address_list;
        }
      })
          .catch(error => {
            console.log(error);
          })
    },
    // 新增
    handleAdd: function () {
      this.dialogVisible1 = true;
    },
    //修改
    handleEdit(index, row) {
      this.updateAddress.id = row.id;
      this.updateAddress.address = row.address;
      this.updateAddress.name = row.name;
      this.updateAddress.phone = row.phone;
      this.updateAddress.isDefault = row.isDefault;
      this.dialogVisible2 = true;
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('确认删除这条地址记录？')
          .then(_ => {
            this.$axios({
              method: 'get', url: '/user/address/delete', params: {
                addId: row.id
              }
            }).then(response => {
              if (response.data.success) {
                this.getAddressList();
              } else {
                console.log(response.data.message);
              }
            })
                .catch(error => {
                  console.log(error)
                });
          })
          .catch(_ => {
          });
    },
    //设置默认地址
    setDefault(row) {

      for (var i = 0; i < this.addressData.length; i++) {
        if (this.addressData[i].id != row.id && this.addressData[i].isDefault == true) {
          this.addressData[i].isDefault = false;
        }
      }
      this.axios({
        method: 'get', url: '/user/defaultadd', params: {
          addId: row.id
        }
      }).then(response => {
        if (response.data.success) {
          this.getAddressList();
        } else {
          row.isDefault = !row.isDefault;
        }
      }).catch(error => {
        console.log(error);
      });

    },
    //关闭新增地址弹框
    handleClose(done) {
      done();
    },
    // 新增地址
    onAdd() {
      this.$refs.newAddressRef.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: '/user/newaddress',
            data: {
              userId: this.$store.state.user.id,
              address: this.newAddress.address,
              name: this.newAddress.name,
              phone: this.newAddress.phone,
              isDefault: false,
              createTime: new Date().getTime()
            }
          }).then(response => {
            if (response.data.success) {
              this.getAddressList();
            } else {
              console.log(response.data.message);
            }
          })
              .catch(error => {
                console.log(error);
              });
          this.dialogVisible1 = false;
        } else {
          return this.$message.error("信息填写不完整！");
        }
      })

    },
    //修改
    update() {
      this.$refs.updateAddressRef.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: '/user/updateaddress',
            data: {
              id: this.updateAddress.id,
              address: this.updateAddress.address,
              name: this.updateAddress.name,
              phone: this.updateAddress.phone,
              isDefault: this.updateAddress.isDefault,
              modifyTime: new Date().getTime()
            }
          }).then(response => {
            if (response.data.success) {
              this.getAddressList();
            } else {
              console.log(response.data.message);
            }
          }).catch(error => {
            console.log(error);
          });
          this.dialogVisible2 = false;
        } else {
          return this.$message.error("信息填写不完整！");
        }

      })
    }
  }
}
</script>

<style scoped>

</style>
